# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

library(scatterplot3d)
library(optparse)
library(ropls)
library(magrittr)
library(tidyverse)


createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

option_list <- list(
  make_option("--i", default = "AllMet.csv", type = "character", help = "metabolite data file"),
  make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
  make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file")
)
opt <- parse_args(OptionParser(option_list = option_list))

sampleIds <- read.csv(opt$g, header = T, stringsAsFactors = F) %>%
  select(c("SampleID", "ClassNote")) %>%
  .$SampleID

data <- read.csv(opt$i, header = T) %>%
  select(-c("HMDB", "KEGG", "Class")) %>%
  select(c("Metabolite", sampleIds)) %>%
  gather("Sample", "Value", -Metabolite) %>%
  spread(Metabolite, "Value") %>%
  column_to_rownames("Sample") %>%
  as.data.frame()

parent <- "./"
createWhenNoExist(parent)
crossValI <- min(nrow(data), 7)

b <- F

while (!b) {
  tryCatch({
    pcaRs <<- opls(data, plotL = F, crossvalI = crossValI)
    b <- T
  }, error = function(e) {
    data <<- data * 10
    b <<- F
  })
}

df <- pcaRs@modelDF %>%
  as_tibble()
if (nrow(df) < 3) {
  pcaRs <- opls(data, plotL = F, crossvalI = crossValI, predI = 3)
}

parameterData <- pcaRs@modelDF %>%
  select(c(1:2)) %>%
  set_colnames(c("R2", "Cumulative R2")) %>%
  mutate(pcName = paste0("PC", 1:n())) %>%
  filter(pcName %in% str_c("PC", 1:5)) %>%
  as_tibble() %>%
  column_to_rownames("pcName") %>%
  t()

print("=in=")
print(parameterData)

write.csv(parameterData, paste0(parent, "/PCA_R2.csv"), quote = FALSE)

pcData <- pcaRs@scoreMN %>%
  as.data.frame() %>%
  rownames_to_column("SampleID") %>%
  select("SampleID", num_range("p", 1:5)) %>%
  rename_at(vars(-c("SampleID")), function(x) {
    str_replace(x, "p", "PC")
  }) %>%
  column_to_rownames("SampleID")

write.csv(pcData, paste0(parent, "/PCA_Score.csv"), quote = FALSE)
